package com.chj.design.sk;

// https://blog.csdn.net/pange1991/article/details/81183634
// https://blog.csdn.net/pange1991/article/details/81183634
public class Code07_Mediator {

	// 定义抽象Mediator,可以与买家和卖家进行联络
	public static abstract class Mediator {
		public abstract void contact(String content, Trader trader);
	}

	public static class Trader {
		protected String name;
		protected Mediator mediator;

		public Trader(String name, Mediator mediator) {
			this.name = name;
			this.mediator = mediator;
		}
	}

	// 租客
	public static class TraderA extends Trader {

		// 具体同事类继承自Trader,此刻就可以与中介者mediator进行通信了
		public TraderA(String name, Mediator mediator) {
			super(name, mediator);
		}

		public void getMessage(String message) {
			System.out.println("租客A: " + name + ", 获得信息: " + message);
		}

		// 租客A与中介者通信
		public void contact(String message) {
			mediator.contact(message, this);
		}
	}

	// 房东
	public static class TraderB extends Trader {

		public TraderB(String name, Mediator mediator) {
			super(name, mediator);
		}

		public void getMessage(String message) {
			System.out.println("房东B: " + name + ", 获得信息: " + message);
		}

		// 房东B与中介者通信
		public void contact(String message) {
			mediator.contact(message, this);
		}
	}

	// 定义具体中介者ConcreteMediator,具体中介者通过协调租客和房东方实现协作行为，了解并维护它的各个交易方。
	public static class ConcreteMediator extends Mediator {
		TraderA traderA;
		TraderB traderB;

		public void setTraderA(TraderA traderA) {
			this.traderA = traderA;
		}

		public void setTraderB(TraderB traderB) {
			this.traderB = traderB;
		}

		@Override
		public void contact(String content, Trader trader) {
			if (trader == traderA) {
				traderB.getMessage(content);
			} else {
				traderA.getMessage(content);
			}
		}
	}

	public static void main(String[] args) {
		// 定义中介者
		ConcreteMediator mediator = new ConcreteMediator();
		// 定义具体交易者
		TraderA traderA = new TraderA("张三", mediator);
		TraderB traderB = new TraderB("李四", mediator);
		// 中介者知晓每一个具体的交易者
		mediator.setTraderA(traderA);
		mediator.setTraderB(traderB);
		traderA.contact("我是租客，3000太贵了，能便宜500不？");
		traderB.contact("我是房东，底价2800，不能再少了！");
	}
}
